const Koa = require('koa');
const app = new Koa();
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId ;
const router = new Router();
const session = require('koa-session');
const koaBody = require('koa-body');
const fs = require('fs');
const Path = require('path');



app.use(koaBody({
  multipart: true,
  formidable: {
    maxFileSize: 20000*1024*1024    // 设置上传文件大小最大限制，默认2M
  }
}));


app.keys = ['secret session'];
const CONFIG = {
  key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
};


app.use(session(CONFIG, app));


app.use(bodyParser());
app.use(cors({
  origin: '*',
  credentials: true
}));

const getTable = async (connectionName) => {
  const client = await MongoClient.connect(`mongodb://ccimm.top:27017`, {
    useNewUrlParser : true,
    useUnifiedTopology: true,
    user: 'admin',
    password: 'admin',
  });
  const db = client.db('shop');
  return {
    db: db.collection(connectionName),
    client : client,
  };
};

router.prefix('/api');

router.get('/banner', async (ctx, next) => {
  const bannerDB = await getTable('banner');
  let bannerArr = [];
  (await bannerDB.db.find({}).toArray()).map((item) => {
    bannerArr.push(item.url);
  });
  ctx.body = bannerArr;
  bannerDB.client.close();
  await next();
});

router.get('/baby', async (ctx, next) => {
  const babyDB = await getTable('baby');
  let babyArr = [];
  (await babyDB.db.find({}).toArray()).map((item) => {
    babyArr.push(item);
  });
  ctx.body = babyArr;
  babyDB.client.close();
  await next();
});

router.get('/shape', async(ctx, next) => {
  const shapeDB = await getTable('shape');
  let shapeArr = [];
  (await shapeDB.db.find({}).toArray()).map((item) => {
    shapeArr.push(item);
  });
  ctx.body = shapeArr;
  shapeDB.client.close();
  await next();
});

router.get('/tabTitle', async(ctx, next) => {
  const tabTitleDB = await getTable('tabTitle');
  let tabTitleArr = [];
  (await tabTitleDB.db.find({}).toArray()).map((item) => {
    tabTitleArr.push(item);
  });
  ctx.body = tabTitleArr;
  tabTitleDB.client.close();
  await next();
});

router.get('/tabContent', async(ctx, next) => {
  const tabContentDB = await getTable('tabContent');
  let tabContentArr = [];
  (await tabContentDB.db.find({}).toArray()).map((item) => {
    tabContentArr.push(item);
  });
  ctx.body = tabContentArr;
  tabContentDB.client.close();
  await next();
});

router.get('/brandContent', async(ctx, next) => {
  const brandContentDB = await getTable('brandContent');
  let brandContentArr = [];
  (await brandContentDB.db.find({}).toArray()).map((item) => {
    brandContentArr.push(item);
  });
  ctx.body = brandContentArr;
  brandContentDB.client.close();
  await next();
});

router.get('/teacherContent', async(ctx, next) => {
  const teacherContentDB = await getTable('teacherContent');
  let teacherContentArr = [];
  (await teacherContentDB.db.find({}).toArray()).map((item) => {
    const { _id, ...foo } = item;
    teacherContentArr.push(foo);
  });
  ctx.body = teacherContentArr;
  teacherContentDB.client.close();
  await next();
});

router.get('/classContent', async(ctx, next) => {
  const classContentDB = await getTable('classContent');
  let classContentArr = [];
  (await classContentDB.db.find({}).toArray()).map((item) => {
    const { _id, ...foo } = item;
    classContentArr.push(foo);
  });
  ctx.body = classContentArr;
  classContentDB.client.close();
  await next();
});


router.get('/classImg', async(ctx, next) => {
  const classImgDB = await getTable('classImg');
  let classImgArr = [];
  (await classImgDB.db.find({}).toArray()).map((item) => {
    const { _id, ...foo } = item;
    classImgArr.push(foo);
  });
  ctx.body = classImgArr;
  classImgDB.client.close();
  await next();
});

router.get('/contentUser', async(ctx, next) => {
  const { type } = ctx.query;
  const contentUserDB = await getTable('user');
  let contentUserArr = [];
  if ( type === 'all' ) {
    (await contentUserDB.db.find({}).toArray()).map((item) => {
      contentUserArr.push(item);
    });
  } else if (type === 'show') {
    (await contentUserDB.db.find({type: 1}).toArray()).map((item) => {
      contentUserArr.push(item);
    });
  }

  ctx.body = contentUserArr;
  contentUserDB.client.close();
  await next();
});



router.get('/queryContent', async(ctx, next) => {
  const { city } = ctx.query;
  const queryContentDB = await getTable('queryContent');
  let queryContentArr = [];
  (await queryContentDB.db.find(city ? {bigCity: city} : {}).toArray()).map((item) => {
    const { _id, ...foo } = item;
    queryContentArr.push(foo);
  });
  ctx.body = queryContentArr;
  queryContentDB.client.close();
  await next();
});


router.post('/addUser', async (ctx, next) => {
  const classUserDB = await getTable('user');
  const res = await classUserDB.db.insertMany([ctx.request.body]);
  classUserDB.client.close();
  if (res.insertedCount === 1) {
    ctx.body = {
      result: 'success'
    }
  }
  await next();
});


router.post('/login', async (ctx, next) => {
  const adminDB = await getTable('admin');
  const { username, password } = ctx.request.body;
  const queryRes = (await adminDB.db.find({username, password}).toArray()).map(item => {
    const { nickname } = item;
    return { nickname };
  });
  if (queryRes.length === 0 ) {
    ctx.body= {
      code: 1,
      err: '用户名或密码错误',
    }
  } else {
    ctx.session.user = {
      isLogin: true,
    };
    ctx.body = {
      code: 0,
      message: '登录成功',
    };
  }

  adminDB.client.close();

  await next();
});

router.post('/isLogin', async (ctx, next) => {
  if (ctx.session.user && ctx.session.user.isLogin) {
    ctx.body = {
      code: 11,
      message: '登录成功',
    }
  } else {
    ctx.body = {
      code: 12,
      message: '未登录'
    }
  }
});


// 拦截判断是否登录
router.all('/admin/*',  async (ctx, next) => {
  if (ctx.session.user && ctx.session.user.isLogin) {
    await next();
  } else {
    ctx.body = {
      code: 401,
      message: 'need auth!'
    }
  }
});

router.post('/admin/modBaby', async (ctx, next) => {
  const { _id, ...res } = ctx.request.body;
  const babyDB = await getTable('baby');
  await babyDB.db.updateOne({"_id": ObjectId(_id)}, {$set:res});
  babyDB.client.close();
  ctx.body = {
    code: 0,
    message: '更新成功',
  };
  await next();
});

router.post('/admin/modShape', async (ctx, next) => {
  const { _id, ...res } = ctx.request.body;
  const shapeDB = await getTable('shape');
  await shapeDB.db.updateOne({"_id": ObjectId(_id)}, {$set:res});
  shapeDB.client.close();
  ctx.body = {
    code: 0,
    message: '更新成功',
  };
  await next();
});

router.post('/admin/modBrand', async (ctx, next) => {
  const { _id, ...res } = ctx.request.body;
  const brandDB = await getTable('brandContent');
  await brandDB.db.updateOne({"_id": ObjectId(_id)}, {$set:res});
  brandDB.client.close();
  ctx.body = {
    code: 0,
    message: '更新成功',
  };
  await next();
});


router.post('/admin/modTabTitle', async (ctx, next) => {
  const { _id, ...res } = ctx.request.body;
  const tabTitleDB = await getTable('tabTitle');
  await tabTitleDB.db.updateOne({"_id": ObjectId(_id)}, {$set:res});
  tabTitleDB.client.close();
  ctx.body = {
    code: 0,
    message: '更新成功',
  };
  await next();
});


router.post('/admin/modTabContent', async (ctx, next) => {
  const { _id, ...res } = ctx.request.body;
  const tabContentDB = await getTable('tabContent');
  await tabContentDB.db.updateOne({"_id": ObjectId(_id)}, {$set:res});
  tabContentDB.client.close();
  ctx.body = {
    code: 0,
    message: '更新成功',
  };
  await next();
});

// 删除用户接口
router.get('/admin/user/delete', async(ctx, next) => {
  const { id } = ctx.query;
  const contentUserDB = await getTable('user');
  await contentUserDB.db.deleteOne({_id: ObjectId(id)});
  ctx.body = {
    code: 0,
    message: '删除成功',
  };
  contentUserDB.client.close();
  await next();
});

// 更新用户信息状态（通过申请）
router.get('/admin/user/access', async(ctx, next) => {
  const { id } = ctx.query;
  const contentUserDB = await getTable('user');
  await contentUserDB.db.updateOne({_id: ObjectId(id)}, {$set: {type: 1}});
  ctx.body = {
    code: 0,
    message: '通过成功',
  };
  contentUserDB.client.close();
  await next();
});

// 图片上传接口
router.post('/upload', async (ctx, next) => {
  const {name,path} = ctx.request.files['file'];

  let fileName = Math.random().toString(16).slice(2,10);
  await fs.renameSync(path,Path.resolve(__dirname,`../upload/${fileName}_${name}`));

  ctx.body = {
    code: 0,
    data: {
      filename: `/image/${fileName}_${name}`,
    }
  }
});



app.use(router.routes()).use(router.allowedMethods());

app.listen(8000);
